﻿using log4net;
using log4net.Config;
using log4net.Repository;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;

namespace Sprout.Log
{

    public static class SproutLogExtensions
    {
        public static ILoggerRepository LogRepository { get; set; }
        public static void AddSproutLog(this IServiceCollection services, IConfiguration configuration)
        {
            if (configuration == null) throw new Exception("配置上下文configuration不能为空");
            var repository = 
                LogManager.CreateRepository("NETCoreRepository");  //仓库名称

            if (!File.Exists("log4net.config.xml"))
            {
                throw new Exception("当前目录下不存在日志配置文件log4net.config.xml");
            }
            var loggerName = Assembly.GetEntryAssembly().GetName().Name;

          

            XmlConfigurator.Configure(repository, new FileInfo("log4net.config.xml"));
            services.AddSingleton<ILog>(LogManager.GetLogger(
                repository.Name,loggerName));
        }

        public static string NameOfCallingClass()
        {
            string fullName;
            Type declaringType;
            int skipFrames = 2;
            do
            {
                MethodBase method = new StackFrame(skipFrames, false).GetMethod();
                declaringType = method.DeclaringType;
                if (declaringType == null)
                {
                    return method.Name;
                }
                skipFrames++;
                fullName = declaringType.FullName;
            }
            while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase));

            return fullName;
        }
    }
}
